package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.IdCardUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author alexis
 * @date 2025-09-04
 */
@Service
public
class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private BedMapper bedMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertCheckApplyIn(CheckInApplyDto checkInApplyDto) {
        //1.检查老人是否已经入住
        Elder elderDB = this.elderMapper.selectOne(new LambdaQueryWrapper<Elder>()
                .eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo()));
        //是，则抛出业务异常，结束方法   否，则继续
        if(elderDB != null && elderDB.getStatus() != 5){
            throw new ServiceException("该老人已入住，请勿重复入住！" );
        }
        //2.更新床位状态为已入住
        //TODO
        Bed bed = updateBedStatus(checkInApplyDto);
        //3.新增或更新老人数据
        Elder elder = insertOrUpdateElder(checkInApplyDto, bed, elderDB);
        //4.新增签约办理
        insertContract(checkInApplyDto, elder);

        //5.新增入住信息
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        Bed bedDB = this.bedMapper.selectById(checkInConfigDto.getBedId());
        checkIn.setBedNumber(bedDB.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setRemark(JSONUtil.toJsonStr(checkInApplyDto.getElderFamilyDtoList()));//老人家属信息
        this.checkInMapper.insert(checkIn);



        //6.新增入住配置信息
        insertCheckInConfig(checkInApplyDto, checkIn);
        return 1;
    }

    @Override
    public CheckInDetailVo selectCheckInDetail(Long id) {
        CheckInDetailVo vo = new CheckInDetailVo();
        //1.查询入住信息
        CheckIn checkIn = this.checkInMapper.selectById(id);
        //2.查询老人信息
        Elder elder = this.elderMapper.selectById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyBeanProp(checkInElderVo, elder);
        int age = IdCardUtils.getAgeByIdCard(elder.getIdCardNo());
        checkInElderVo.setAge(age);
        vo.setCheckInElderVo(checkInElderVo);
        //3.查询合同信息
        Contract contract = this.contractMapper.selectOne(new LambdaQueryWrapper<Contract>()
                .eq(Contract::getElderId, checkIn.getElderId()));
        vo.setContract(contract);
        //4.查询入住配置信息
        CheckInConfig checkInConfig = this.checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>()
                .eq(CheckInConfig::getCheckInId, checkIn.getId()));
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyBeanProp(checkInConfigVo, checkInConfig);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        vo.setCheckInConfigVo(checkInConfigVo);
        //5.家属列表
        String remark = checkIn.getRemark();
        //json字符串==>List<ElderFamily>
        List<ElderFamilyVo> elderFamilyVoList = JSONUtil.toList(remark, ElderFamilyVo.class);
        vo.setElderFamilyVoList(elderFamilyVoList);

        return vo;
    }

    private void insertCheckInConfig(CheckInApplyDto checkInApplyDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyBeanProp(checkInConfig, checkInApplyDto.getCheckInConfigDto());
        checkInConfig.setCheckInId(checkIn.getId());
        this.checkInConfigMapper.insert(checkInConfig);
    }

    private @NotNull Bed updateBedStatus(CheckInApplyDto checkInApplyDto) {
        Long bedId = checkInApplyDto.getCheckInConfigDto().getBedId();
        Bed bed = this.bedMapper.selectById(bedId);
        if(bed==null ||bed.getBedStatus() == 1 ){
            throw new ServiceException("床位不存在或床位已被占用，请重新选择！！！");
        }
        bed.setBedStatus(1);
        this.bedMapper.updateById(bed);
        return bed;
    }

    private void insertContract(CheckInApplyDto checkInApplyDto, Elder elder) {
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();
        Contract contract = new Contract();
        BeanUtils.copyBeanProp(contract, checkInContractDto);
        //补全数据
        contract.setElderId(elder.getId());//老人ID
        String contractNo = "HT"+CodeGenerator.generateContractNumber();
        contract.setContractNumber(contractNo);//合同编号

        contract.setElderName(elder.getName());//老人姓名
        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getStartDate();
        contract.setStartDate(startDate);
        LocalDateTime endDate = checkInApplyDto.getCheckInConfigDto().getEndDate();
        contract.setEndDate(endDate);
        Integer status =startDate.isBefore(LocalDateTime.now())?1:0;
        contract.setStatus(status);//状态 (0: 未生效, 1: 已生效, 2: 已过期, 3: 已失效)
        this.contractMapper.insertContract(contract);
    }

    private @NotNull Elder insertOrUpdateElder(CheckInApplyDto checkInApplyDto, Bed bed, Elder elderDB) {
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        Elder elder = new Elder();
        BeanUtils.copyBeanProp(elder, checkInElderDto);
        elder.setStatus(1);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        if(elderDB !=null){
            elder.setId(elderDB.getId());
            this.elderMapper.updateById(elder);
        }else{
            this.elderMapper.insert(elder);
        }
        return elder;
    }

}
